<?php

namespace app\api\controller\yalimedia;

use addons\yalimedia\library\Service;
use app\admin\model\yalimedia\course\Contentlog;
use app\admin\model\yalimedia\Order;
use app\admin\model\yalimedia\Uservip;
use app\admin\model\yalimedia\Vipcard;
use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Exception;
use Yansongda\Pay\Exceptions\GatewayException;

/**
 * 用户接口
 */
class User extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['appid','authUser'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     *获取APPID
     */
    public function appid(){
        $config = get_addon_config('yalimedia');
        $mp = $config['mp'];
        $appid = empty($mp['appid'])?'':$mp['appid'];
        
        $this->success('请求成功',['appid'=>$appid]);
    }

    /**
     * 微信h5授权登录
     */
    public function authUser(){

        $config = get_addon_config('yalimedia');
        $mp = $config['mp'];
        $options = array(
            'app_id'    => $mp['appid'], //填写高级调用功能的app id
            'secret'    => $mp['appsecret'] //填写高级调用功能的密钥
        );

        $app = Factory::officialAccount($options);
        $oauth = $app->oauth;

        $user = $oauth->user();

        if($user){
            $loginret = Service::connect('mp',['openid'=>$user['original']['openid'],'headimgurl'=>$user['avatar'],'nickname'=>$user['nickname'],'type'=>'mp']);

            if ($loginret) {
                $_userinfo = $this->auth->getUserinfo();

                $data = [
                    'user_id'=> $_userinfo['id'],
                    'avatarUrl'=> $user['avatar'],
                    'nickName'=> $user['nickname'],
                    'token'  => $_userinfo['token']
                ];

                $this->success(__('登录成功'), $data);
            }
            $this->error('请求失败');
        }
    }


    /**
     * 获取会员卡列表
     */
    public function vip_card(){
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');

        $subject = new \addons\yalimedia\service\Vipcard();
        $data = $subject->getVipcardList($page,$limit);

        $this->success('请求成功', $data);
    }

    /**
     * 购买VIP
     */
    public function buy_vip(){

        $id = $this->request->post('id');
        $vipCardModel = new Vipcard();
        $vipCard = $vipCardModel->where(['id'=>$id])->find();
        if(empty($vipCard)){
            $this->error("当前会员卡不存在");
        }

        $tool = new \addons\yalimedia\service\Tool();
        $order_no = $tool->create_sn();

        $orderModel = new Order();
        if($orderModel->save([
            'order_no'=>$order_no,
            'user_id'=>$this->auth->id,
            'type'=>2,
            'price'=>$vipCard['price'],
            'item_id'=>$id
        ])){
            try {
                $wechatUser = \app\admin\model\yalimedia\Wechat::get(['user_id' => $this->auth->id,'type' =>'mp']);
                $params = [
                    'amount'=>$vipCard['price'],
                    'orderid'=>$order_no,
                    'type'=>"wechat",
                    'title'=>$vipCard['name'],
                    'notifyurl'=>$this->request->domain()."/api/yalimedia/block/notifyx",
                    'returnurl'=>"",
                    'method'=>"mp",
                    'openid'=>$wechatUser['openid'],
                ];
                $info = get_addon_info('epay');
                if(empty($info)){
                    $this->error('请到后台插件管理安装《微信支付宝整合》插件');
                }

                $result = \addons\epay\library\Service::submitOrder($params);
            }catch (GatewayException $e){
                $this->error($e->getMessage());
            }

            $this->success('请求成功',$result);
        }else{
            $this->success('请求失败，请稍后再试');
        }
    }

    /**
     * 获取用户VIp信息
     */
    public function vip(){
        $userVipModel = new Uservip();
        $userVip = $userVipModel->where(['user_id'=>$this->auth->id])->find();
        if($userVip){
            if($userVip['expiretime'] === 0){
                $return = ['vip'=>1,'expiretime'=>$userVip['expiretime']];
            }else{
                if($userVip['expiretime']>time()){
                    $return = ['vip'=>1,'expiretime'=>$userVip['expiretime']];
                }else{
                    $return = ['vip'=>0];
                }
            }


        }else{
            $return = ['vip'=>0];
        }
        $this->success('请求成功',$return);
    }

    //获取学习记录
    public function record(){
        $page = $this->request->post('page');
        $limit = $this->request->post('limit');

        $course = new \addons\yalimedia\service\Course();
        $data = $course->getContentLogList($this->auth->id,$page,$limit);

        foreach($data['data'] as &$v){
            $v['cover'] = $this->request->domain().$v['cover'];
        }
        $this->success('请求成功', $data);
    }

}
